<script lang="ts" setup>
import type { RowType } from '../../types';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';
import { $t } from '@vben/locales';
import { useVbenForm } from '#/adapter/form';
import { postSlides, putSlides } from '#/api/admin/slides';
import { getSlidesThemes } from '#/api/admin/slidesTheme';
 
import {
  getThemesFiles,
} from '#/api/admin/theme';

const themeOptions = ref([{ label: '请选择主题', value: 0 }]);

// 获取主题数据
const fetchThemes = async () => {
  try {
    const res = await getThemesFiles('default');
    const themes = res.data.list.map((item: any) => ({
      label: item.name, // 根据实际接口返回的字段调整
      value: item.id
    }));
    // 将“请选择主题”追加到前面
    themeOptions.value = [{ label: $t('admin.pleaseSelectPage'), value: 0 }, ...themes];
  } catch (error) {
    message.error('获取页面列表失败');
  }
};

// 组件挂载时获取主题
onMounted(() => {
  fetchThemes();
});
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'name',
      label: $t('admin.slideName'),
      rules: 'required',
    },
  {
      component: 'Select',
      defaultValue: 0,
      componentProps: {
        placeholder: $t('admin.pleaseSelectPage'),
        options: themeOptions, // 使用响应式的主题选项
         class: 'w-full',
      },
      fieldName: 'page', // 假设字段名为theme_id
      label: $t('admin.Page'),
       rules: 'required',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'remark',
      label: $t('admin.Remark'),
    },
  ],
  showDefaultActions: false,
});
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
    formModalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: RowType = formModalApi.getData();
      if (values) {
        formApi.setValues(values);
      }
    }
  },
});

async function onSubmit(values: Record<string, any>) {
  function showMsg(msg: string) {
    message.success(msg);
    formModalApi.setData({ isUpdata: true });
  }
  if (values.id) {
    const { msg } = await putSlides(values);
    showMsg(msg);
  } else {
    const { msg } = await postSlides(values);
    showMsg(msg);
  }
}
</script>
<template>
  <Modal class="w-3/5">
    <Form />
  </Modal>
</template>

<style lang="scss" scoped></style>
